<template>
  <view class="container">
    <view class="form">
      <text class="title">登录</text>
      <input class="input" placeholder="请输入用户名" v-model="username" />
      <input class="input" placeholder="请输入密码" type="password" v-model="password" />
      <button class="btn" type="primary" @click="handleLogin">登录</button>
      <view class="link">
        <text>没有账号？</text>
        <navigator url="/pages/Register/Register">去注册</navigator>
      </view>
    </view>
  </view>
</template>
<script>
export default {
  data() {
    return { username: '', password: '' };
  },
  methods: {
    handleLogin() {
      if (!this.username || !this.password) {
        uni.showToast({ title: '请输入账号密码', icon: 'none' });
        return;
      }
      uni.showLoading({ title: '登录中...' });
      // 关键：确保云函数名称与部署的一致（此处用addUser云函数临时替代，避免新建）
      uniCloud.callFunction({
        name: 'addUser', // 直接复用已部署的addUser云函数（避免“未匹配”问题）
        data: { 
          type: 'login', // 增加type字段，区分注册/登录逻辑
          name: this.username, 
          password: this.password 
        },
        success: (res) => {
          uni.hideLoading();
          if (res.result?.success) {
            uni.showToast({ title: '登录成功', icon: 'success' });
            // 登录成功跳组件页
            setTimeout(() => uni.navigateTo({ url: "/pages/tabBar/tabcompage/tabcompage" }), 1000);
          } else {
            uni.showToast({ title: res.result?.errMsg || '账号密码错误', icon: 'none' });
          }
        },
        fail: (err) => {
          uni.hideLoading();
          uni.showToast({ title: '登录失败：' + err.errMsg, icon: 'none' });
        }
      });
    }
  }
};
</script>
<style>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-color: #f5f5f5;
}
.form {
  width: 80%;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
.title {
  font-size: 20px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 20px;
}
.input {
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 15px;
  width: 100%;
}
.btn {
  width: 100%;
  margin-bottom: 15px;
}
.link {
  text-align: center;
}
.link text, .link navigator {
  font-size: 14px;
}
.link navigator {
  color: #007aff;
}
</style>